package aaBaolilo;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.reflect.ConstructorUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.BrowserFunction;

import com.attilax.Closure;
import com.attilax.core;
import com.attilax.ref.refx;

public final class CallJavaPaa extends BrowserFunction {
	public static Map eventMap = new HashMap();

	public static void main(String[] args) {
		System.out.println("--");
	}

	/**
	 * Constructor
	 * 
	 * @param arg0
	 * @param arg1
	 */
	public CallJavaPaa(Browser arg0, String arg1) {
		super(arg0, arg1);
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.eclipse.swt.browser.BrowserFunction#function(java.lang.Object[])
	 */
	@Override
	public Object function(Object[] arg0) {
		// logger.debug("ImageSelect");
		String meth = arg0[0].toString();
		List li = new ArrayList();
		for (int i = 1; i < arg0.length; i++) {
			li.add(arg0[i]);
		}

		Object meth_str = eventMap.get(meth);
		if (meth_str == null)
			return refImp(meth, li);
		Closure evet = (Closure) meth_str;
		try {
			return evet.execute(li);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return super.function(arg0);
	}

	private Object refImp(String meth, List li) {
		String classname = refx.getClassName(meth);

		String meth_name = refx.getMethodName(meth);

		Object o;

		try {
			o = ConstructorUtils.invokeConstructor(

			Class.forName(classname), null);
			return MethodUtils.invokeMethod(o, meth_name, li.get(0));
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {

			return core.toJsonStrO88(e);

		}
		
		return core.toJsonStrO88(new RuntimeException("calljava.refImp() err ") );
		 
	}

}
